
#include "appinc.h"

static void __inline__ _timespec_add_ms(struct timespec *tv, int ms)
{
	tv->tv_sec += ms/1000;
	tv->tv_nsec += (ms%1000)*1000000;
	if (tv->tv_nsec > 1000000000) {
		tv->tv_nsec -= 1000000000;
		tv->tv_sec += 1;
	}
}


/* 初始化一个event */
int libnotify_init(notify_event_t *event)
{
	pthread_condattr_t cattr;

	if (event == NULL)
		return -EINVAL;
	
	memset(event, 0, sizeof(notify_event_t));
	pthread_condattr_init(&cattr); 
	pthread_condattr_setclock(&cattr, CLOCK_MONOTONIC);
	pthread_mutex_init(&event->mutex, NULL);
	pthread_cond_init(&event->cond, &cattr);

	return 0;
}

/* 等待事件,标志有变化则退出
timeout: 等待的超时时间，单位：ms, 如果<=0, 表示一直等待
return: 0：等待成功
*/
int libnotify_wait(notify_event_t *event, int timeout)
{
	int ret = 0;
	struct timespec tv;
	
	if (event == NULL)
		return -1;
	if (timeout > 0) {
		clock_gettime(CLOCK_MONOTONIC, &tv);
		_timespec_add_ms(&tv, timeout);
	}

	pthread_mutex_lock(&event->mutex);
	if (timeout <= 0)
		ret = pthread_cond_wait(&event->cond, &event->mutex);
	else
		ret = pthread_cond_timedwait(&event->cond, &event->mutex, &tv);
	pthread_mutex_unlock(&event->mutex);

	return ret;
}


/* 产生空事件 */
int libnotify_wakeup(notify_event_t *event)
{
	if (event == NULL)
		return -1;
	
	pthread_mutex_lock(&event->mutex);
	pthread_cond_broadcast(&event->cond);
	pthread_mutex_unlock(&event->mutex); 

	return 0;
}

